<template>
<div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card class="box-card">
        <el-row>
            <el-alert
                    title="注意：只允许选择三级分类设置相关参数！"
                    type="warning"
                    :closable="false"
                    show-icon>
            </el-alert>
        </el-row>
        <el-row>
            <span>选择商品分类：</span>
            <el-cascader
                    v-model="selectedKeys"
                    :options="goodsCateList"
                    :props="cascaderProps"
                    @change="cateChanged" clearable></el-cascader>
        </el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-row>
                <el-button :disabled="isBtnDisabled" type="primary" @click="showAddParamsDialog">添加属性</el-button>
            </el-row>
            <!--动态参数-->
            <el-tab-pane label="动态参数" name="many">
                <el-table :data="dynamicParams">
                    <!--展开行-->
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="removeParamsVals(i,scope.row)">{{item}}</el-tag>
                            <!--添加参数项-->
                            <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="#" type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showSetAttrDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttr(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!--静态属性-->
            <el-tab-pane label="静态属性" name="only">
                <el-table :data="staticParams">
                    <!--展开行-->
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="removeParamsVals(i,scope.row)">{{item}}</el-tag>
                            <!--添加参数项-->
                            <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="#" type="index"></el-table-column>
                    <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showSetAttrDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttr(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <!--添加参数对话框-->
    <el-dialog
            :title="titleText"
            :visible.sync="addParamsDialogVisible"
            width="50%" @close="addParamsDialogClosed">
        <el-form :model="addParamsForm" :rules="paramsRules" ref="addParamsRef" label-position="right" label-width="80px">
            <el-form-item prop="attr_name" :label="labelText">
                <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="addParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
    </el-dialog>

    <!--编辑参数对话框-->
    <el-dialog
            :title="titleText"
            :visible.sync="editParamsDialogVisible"
            width="50%" @close="editParamsDialogClosed">
        <el-form :model="editParamsForm" :rules="paramsRules" ref="editParamsRef" label-position="right" label-width="80px">
            <el-form-item prop="attr_name" :label="labelText">
                <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="editParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams()">确 定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
    export default {
        name: "Params",
        data(){
            return{
                //添加参数数据
                addParamsDialogVisible:false,
                addParamsForm:{
                    attr_name:'',
                    attr_sel: '',
                    attr_vals:''
                },
                paramsRules:{
                    attr_name:[{required:true,message:'请输入参数名',trigger:"blur"}]
                },
                //编辑数据
                editParamsDialogVisible:false,
                editParamsForm:{
                    attr_name:'',
                    attr_sel: '',
                    attr_vals:''
                },

                //分类cascader数据
                selectedKeys:[],
                currnetCateId:0,
                goodsCateList:[],
                cascaderProps:{
                    value:'cat_id',
                    label:'cat_name',
                    children:'children',
                    expandTrigger: 'hover',
                },
                //tabs数据
                activeName:'many',
                dynamicParams:[],
                staticParams:[],

            }
        },
        created() {
            this.getCateList()
        },
        computed:{
            isBtnDisabled(){
                return this.currnetCateId === 0
            },
            titleText(){
                return this.activeName == 'many'?'添加动态参数':'添加静态属性'
            },
            labelText(){
                return this.activeName == 'many'?'动态参数':'静态属性'
            }
        }
        ,
        methods:{
            async getCateList(){
                const {data:res} = await this.$http.get('/categories')
                if(res.meta.status !== 200) return this.$message.error("获取商品分类失败")
                this.goodsCateList = res.data
            },
            //获取参数
            async getParams(id){
                //获取动态参数
                if(this.activeName == 'many'){
                    const {data:dynamicRes} = await this.$http.get(`categories/${this.currnetCateId}/attributes`,{params:{sel:'many'}})
                    if(dynamicRes.meta.status !== 200) return this.$message.error("获取动态参数失败")
                    dynamicRes.data.forEach(item=>{
                        item.attr_vals = item.attr_vals?item.attr_vals.split(','):[]
                        /*给每一列的参数项绑定自身的参数，不然会联动*/
                        item.inputVisible = false
                        item.inputValue = ''
                    })
                    this.dynamicParams = dynamicRes.data
                    //console.log(this.dynamicParams)
                    //获取静态参数
                }else {
                    const {data:staticRes} = await this.$http.get(`categories/${this.currnetCateId}/attributes`,{params:{sel:'only'}})
                    //console.log(staticRes)
                    if(staticRes.meta.status !== 200) return this.$message.error("获取动态参数失败")
                    this.staticParams = staticRes.data
                    //console.log(this.staticParams)
                }
            },
            //获取当前的分类id
            cateChanged(){
                this.currnetCateId = this. selectedKeys[2]
                //console.log(this.selectedKeys)
                this.getParams(this.currnetCateId)

            },
            //tabs当前active改变
            handleClick(){
                this.getParams(this.currnetCateId)
            },
            //显示编辑属性对话框
            showSetAttrDialog(row){
                this.editParamsDialogVisible = true
                this.editParamsForm.attr_name = row.attr_name
                this.editParamsForm.attr_id = row.attr_id
                this.editParamsForm.attr_sel = row.attr_sel

            },
            //编辑属性
            async editParams(){
                const {data:res} = await this.$http.put(`categories/${this.currnetCateId}/attributes/${this.editParamsForm.attr_id}`,this.editParamsForm)
                console.log(res)
                if(res.meta.status !== 200) return this.$message.error("编辑参数失败")
                this.$message.success("编辑参数成功")
                this.getParams()
                this.editParamsDialogVisible = false
            },
            //关闭编辑属性对话框
            editParamsDialogClosed(){
                this.$refs.editParamsRef.resetFields()
            },
            //删除属性
            async removeAttr(row){
                const removeAttrConfirm = await this.$confirm('此操作将永久删除该属性/参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if(removeAttrConfirm !== 'confirm') return
                const {data:res} = await this.$http.delete(`/categories/${this.currnetCateId}/attributes/${row.attr_id}`)
                if(res.meta.status !== 200) return this.$message.error("删除参数失败")
                this.$message.success("删除参数成功")
                this.getParams()
            },
            //添加参数
            addParams(){
                this.$refs.addParamsRef.validate(async (valid)=>{
                    if(!valid) return
                    const {data:res} = await this.$http.post(`categories/${this.currnetCateId}/attributes`,this.addParamsForm)
                    console.log(res)
                    if(res.meta.status !== 201) return this.$message.error("添加动态参数失败")
                    this.getParams()
                    this.$message.success("添加动态参数成功")
                    this.addParamsDialogVisible = false

                })
            },
            //打开添加参数对话框
            showAddParamsDialog(){
                this.addParamsDialogVisible = true
                this.addParamsForm.attr_sel = this.activeName
            },
            //关闭添加参数对话框，清空内容
            addParamsDialogClosed(){
                this.$refs.addParamsRef.resetFields()
            },

            showInput(row){
                row.inputVisible = true
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            //编辑动态参数可选项
            async handleInputConfirm(row) {
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }

                row.attr_vals.push(row.inputValue.trim())

                row.inputValue = ''
                row.inputVisible = false;

                /*将修改发送给后端*/
                this.saveAttrVals(row)
                //this.getParams()

            },
            async saveAttrVals(row){
                const {data:res} = await this.$http.put(`categories/${this.currnetCateId}/attributes/${row.attr_id}`,{
                    attr_name:row.attr_name,
                    attr_sel:row.attr_sel,
                    attr_vals: row.attr_vals.join(',')
                })
                console.log(res)
                if(res.meta.status !== 200) return this.$message.error("修改动参数项失败")
                this.$message.success("修改动参数项成功")
            },
            //删除参数可选项
            removeParamsVals(i,row){
                row.attr_vals.splice(i,1)
                this.saveAttrVals(row)
            }
        }
    }
</script>

<style scoped>
    .el-row{
        margin-bottom: 15px !important;
    }
    .el-tag {
        margin: 0 5px;
    }

</style>
